package web.dao.impls;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import map.beans.MapEngineRegistrationBean;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import web.dao.interfaces.EngineRegistrationDao;

@Repository("EngineRegDao")
@Transactional(readOnly = true)
public class EngineRegistrationDaoImpl implements EngineRegistrationDao {
	private static Logger LOGGER = LoggerFactory.getLogger(EngineRegistrationDaoImpl.class);
	
	@PersistenceContext
	private EntityManager entityManager;
	
	@Override
	@Transactional
	public Long save(MapEngineRegistrationBean engine) {	
		try {
			System.out.println("........... Persisting Object  " + engine.getName() + "  ..............");
			entityManager.persist(engine);
			entityManager.flush();
		} catch (Exception e) {
			LOGGER.error(e.getMessage());		
		}
		return engine.getId();
	}

	@Override
	@Transactional
	public Long update(MapEngineRegistrationBean engine) {
		try {
			System.out.println("........... Updating Object " + engine.getName() + "  ..............");
			entityManager.merge(engine);
			entityManager.flush();
		} catch (Exception e) {
			LOGGER.error(e.getMessage());
		}
		return engine.getId();
	}
	
	@Override
	public List<MapEngineRegistrationBean> findAll() {
		TypedQuery<MapEngineRegistrationBean> query = entityManager.createQuery("SELECT g FROM MapEngineRegistrationBean g ORDER BY g.id",
				MapEngineRegistrationBean.class);
		return query.getResultList();
	}		
	
	@Override
	public boolean delete(MapEngineRegistrationBean engine) {
		// check that it exists in the DB
		engine = entityManager.getReference(MapEngineRegistrationBean.class, engine.getId());
		boolean status = false;
		
		if (engine != null) {					
			entityManager.remove(engine);
			entityManager.flush();
			status = true;
		}
		return status;
	}
	
	@Override
	public MapEngineRegistrationBean getMapEngine(Long id) {
		MapEngineRegistrationBean engine = entityManager.find(MapEngineRegistrationBean.class, id);		
		return engine;
	}	
}
